import React, { useEffect, useState } from 'react'
import { Tabs, Row, Col, Select, Slider, Input, Checkbox } from 'antd'
import FlowGraph from '@/pages/Graph'
// @ts-ignore
import reqwest from 'reqwest'

const { TabPane } = Tabs
const { Option } = Select

enum GRID_TYPE {
  DOT = 'dot',
  FIXED_DOT = 'fixedDot',
  MESH = 'mesh',
  DOUBLE_MESH = 'doubleMesh',
}

enum REPEAT_TYPE {
  NO_REPEAT = 'no-repeat',
  REPEAT = 'repeat',
  REPEAT_X = 'repeat-x',
  REPEAT_Y = 'repeat-y',
  ROUND = 'round',
  SPACE = 'space',
  FLIPX = 'flipX',
  FLIPY = 'flipY',
  FLIPXY = 'flipXY',
  WATERMARK = 'watermark',
}

interface IProps {
  attrs: {
    [key: string]: any
  }
  setAttr: (key: string, value: any) => void
}

const tryToJSON = (val: string) => {
  try {
    return JSON.parse(val)
  } catch (error) {
    return val
  }
}

export default function (props: IProps) {
  const { attrs, setAttr } = props

  const [data, setData] = useState({
    selectList: []
  })
  const [pageType, setPageType] = useState<any>(null)
  const [feedbackMessage, setFeedbackMessage] = useState<any>(null)
  const [result, setResult] = useState<any>(null)
  const [version, setVersion] = useState<any>(null)

  useEffect(() => {
    let options
    if (attrs.type === 'doubleMesh') {
      options = {
        type: attrs.type,
        args: [
          {
            color: attrs.color,
            thickness: attrs.thickness,
          },
          {
            color: attrs.colorSecond,
            thickness: attrs.thicknessSecond,
            factor: attrs.factor,
          },
        ],
      }
    } else {
      options = {
        type: attrs.type,
        args: [
          {
            color: attrs.color,
            thickness: attrs.thickness,
          },
        ],
      }
    }
    const { graph } = FlowGraph
    graph.drawGrid(options)
  }, [
    attrs.type,
    attrs.color,
    attrs.thickness,
    attrs.thicknessSecond,
    attrs.colorSecond,
    attrs.factor,
  ])

  useEffect(() => {
    const { graph } = FlowGraph
    graph.setGridSize(attrs.size)
  }, [attrs.size])

  useEffect(() => {
    const options = {
      color: attrs.bgColor,
      image: attrs.showImage
        ? 'https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*o-MuTpQaj7EAAAAAAAAAAABkARQnAQ'
        : undefined,
      repeat: attrs.repeat,
      angle: attrs.angle,
      size: tryToJSON(attrs.bgSize),
      position: tryToJSON(attrs.position),
      opacity: attrs.opacity,
    }
    const { graph } = FlowGraph
    graph.drawBackground(options)
  }, [
    attrs.bgColor,
    attrs.showImage,
    attrs.repeat,
    attrs.angle,
    attrs.bgSize,
    attrs.position,
    attrs.opacity,
  ])

  //第二个参数是依赖的变量，即这些变量发生改变则再次执行
  useEffect(() => {
    const { pageType, inferenceDialogData } = FlowGraph
    // @ts-ignore
    if (top.DIALOG) {
      // @ts-ignore
      let showId = top.DIALOG.showIds.top();
      if (showId) {
        // @ts-ignore
        let id = top.DIALOG.get(showId).state.data
        if (!pageType && typeof(id) != "string") {
          setVersion(id.history_id)
          id = id.id;
        }
        reqwest({
          method: 'post',
          data: { data: id },
          url: '/OMDS/api/rest/malfunction/getSelections',
          success: function (res: any) {
            if (res.code == 200) {
              setData({ selectList: res.data })
            }
          }
        })
      }
    }
    setPageType(pageType)
    if (inferenceDialogData && inferenceDialogData.result) {
      setResult("" + inferenceDialogData.result)
    }
  }, [])

  const onSelectVersion = (val: string) => {
    const { graph } = FlowGraph
    reqwest({
      method: 'post',
      data: { data: val },
      url: '/OMDS/api/rest/malfunction/changeVersion',
      success: function (res: any) {
        if (res.code == 200) {
          graph.clearCells()
          if (res.data) {
            graph.fromJSON(JSON.parse(res.data))
          }
        }
      }
    })
  }

  const feedbackChange = (e: any) => {
    let value = e.target.value
    setFeedbackMessage(value)

    let { inferenceId, inferenceResultData } = FlowGraph
    if (inferenceId && inferenceResultData) {
      for (let i = 0; i < inferenceResultData.length; i++) {
        let resultData = inferenceResultData[i];
        if (resultData.id == inferenceId) {
          resultData.msg = value
        }
      }
    }
  }

  const resultChange = (val: string, option: any) => {
    FlowGraph.inferenceDialogData.result = val;
    FlowGraph.ininferenceDialogDataResultChange = true;
    setResult(val);

  }

  if (data.selectList.length > 0) {
    return (
      <Tabs defaultActiveKey="0">
        <TabPane tab="历史版本" key="0">
          <Row align="middle">
            <Col span={5}>版本号</Col>
            <Col span={19}>
              <Select style={{ width: '100%' }} onChange={onSelectVersion} value={version}>
                {
                  data.selectList.map(item => (
                    // @ts-ignore
                    <Select.Option value={item.code}>{item.text}</Select.Option>
                  ))
                }
              </Select>
            </Col>
          </Row>
        </TabPane>
      </Tabs>
    )
  } else {
    let feedbackMessage = undefined
    const { inferenceId, inferenceResultData } = FlowGraph

    if (inferenceId && inferenceResultData) {
      for (let i = 0; i < inferenceResultData.length; i++) {
        let resultData = inferenceResultData[i];
        if (resultData.id == inferenceId) {
          feedbackMessage = resultData.msg;
        }
      }
    }
    return (
      <Tabs defaultActiveKey="0">
        {/* && FlowGraph.inferenceId */}
        {
          pageType && pageType == "1" ? <TabPane tab="反馈" key="0">
            {/* <Row align="middle">
              <Col span={24}>反馈信息</Col>
              <Col span={24}>
                <Input.TextArea style={{ width: '100%' }} value={feedbackMessage} onChange={feedbackChange}>
                </Input.TextArea>
              </Col>
            </Row> */}
            <Row align="middle">
              <Col span={24}>反馈信息</Col>
              <Col span={24}>
                <Select style={{ width: '100%' }} onChange={resultChange} value={result}>
                  <Option value="1">正确</Option>
                  <Option value="0">错误</Option>
                </Select>
              </Col>
            </Row>
          </TabPane> : ""
        }
        {/* <TabPane tab="历史版本" key="0">
          <Row align="middle">
            <Col span={5}>版本号</Col>
            <Col span={19}>
              <Select style={{width: '100%'}}>

              </Select>
            </Col>
          </Row>
        </TabPane>*/}
        {/* <TabPane tab="网格" key="1">
          <Row align="middle">
            <Col span={10}>网格类型</Col>
            <Col span={12}>
              <Select
                style={{ width: '100%' }}
                value={attrs.type}
                // @ts-ignore
                onChange={(val) => setAttr('type', val)}
              >
                <Select.Option value={GRID_TYPE.DOT}>Dot</Select.Option>
                <Select.Option value={GRID_TYPE.FIXED_DOT}>
                  Fixed Dot
                </Select.Option>
                <Select.Option value={GRID_TYPE.MESH}>Mesh</Select.Option>
                <Select.Option value={GRID_TYPE.DOUBLE_MESH}>
                  Double Mesh
                </Select.Option>
              </Select>
            </Col>
          </Row>
          <Row align="middle">
            <Col span={10}>网格大小</Col>
            <Col span={10}>
              <Slider
                min={1}
                max={20}
                step={1}
                value={attrs.size}
                onChange={(val: number) => setAttr('size', val)}
              />
            </Col>
            <Col span={2}>
              <div className="result">{attrs.size}</div>
            </Col>
          </Row>
          {attrs.type === 'doubleMesh' ? (
            <React.Fragment>
              <Row align="middle">
                <Col span={10}>Primary Color</Col>
                <Col span={12}>
                  <Input
                    type="color"
                    value={attrs.color}
                    style={{ width: '100%' }}
                    onChange={(e) => setAttr('color', e.target.value)}
                  />
                </Col>
              </Row>
              <Row align="middle">
                <Col span={10}>Primary Thickness</Col>
                <Col span={10}>
                  <Slider
                    min={0.5}
                    max={10}
                    step={0.5}
                    value={attrs.thickness}
                    onChange={(val: number) => setAttr('thickness', val)}
                  />
                </Col>
                <Col span={2}>
                  <div className="result">{attrs.thickness.toFixed(1)}</div>
                </Col>
              </Row>
              <Row align="middle">
                <Col span={10}>Secondary Color</Col>
                <Col span={12}>
                  <Input
                    type="color"
                    value={attrs.colorSecond}
                    style={{ width: '100%' }}
                    onChange={(e) => setAttr('colorSecond', e.target.value)}
                  />
                </Col>
              </Row>
              <Row align="middle">
                <Col span={10}>Secondary Thickness</Col>
                <Col span={10}>
                  <Slider
                    min={0.5}
                    max={10}
                    step={0.5}
                    value={attrs.thicknessSecond}
                    onChange={(val: number) => setAttr('thicknessSecond', val)}
                  />
                </Col>
                <Col span={2}>
                  <div className="result">{attrs.thicknessSecond.toFixed(1)}</div>
                </Col>
              </Row>
              <Row align="middle">
                <Col span={10}>Scale Factor</Col>
                <Col span={10}>
                  <Slider
                    min={1}
                    max={10}
                    step={1}
                    value={attrs.factor}
                    onChange={(val: number) => setAttr('factor', val)}
                  />
                </Col>
                <Col span={2}>
                  <div className="result">{attrs.factor}</div>
                </Col>
              </Row>
            </React.Fragment>
          ) : (
            <React.Fragment>
              <Row align="middle">
                <Col span={10}>表格颜色</Col>
                <Col span={12}>
                  <Input
                    type="color"
                    value={attrs.color}
                    style={{ width: '100%' }}
                    onChange={(e) => setAttr('color', e.target.value)}
                  />
                </Col>
              </Row>
              <Row align="middle">
                <Col span={10}>网格粗细</Col>
                <Col span={10}>
                  <Slider
                    min={0.5}
                    max={10}
                    step={0.5}
                    value={attrs.thickness}
                    onChange={(val: number) => setAttr('thickness', val)}
                  />
                </Col>
                <Col span={1}>
                  <div className="result">{attrs.thickness.toFixed(1)}</div>
                </Col>
              </Row>
            </React.Fragment>
          )}
        </TabPane> */}
      </Tabs>
    )
  }

}
